package com.travel.api;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.travel.config.MinioConfig;
import com.travel.dto.WxUserDTO;
import com.travel.pojo.User;
import com.travel.result.Result;
import com.travel.service.MinioService;
import com.travel.service.UserService;
import com.travel.service.impl.MinioServiceImpl;
import com.travel.utils.AESUtils;
import com.travel.utils.DateUtils;
import com.travel.utils.GetPostUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.binary.Base64;
import org.json.JSONException;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.UnsupportedEncodingException;
import java.security.InvalidAlgorithmParameterException;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

/**
 * @author chendikai
 * @date 2024-07-11 19:36
 */
@RestController
@RequestMapping("/api")
@Api(tags = "获取用户openId")
@Slf4j
public class UserApiController {

    @Value("${pay-platform.wx.pay.appId}")
    private String appId;
    @Value("${pay-platform.wx.pay.secret}")
    private String secret;

    @Autowired
    private UserService userService;

    @Autowired
    private MinioService minioService;
    @GetMapping(value = "/getUser")
    @ApiOperation(value = "获取用户信息", notes = "获取用户信息")
    @ApiImplicitParam(name="id",value = "用户id")
    public Result<User> getUser(@RequestParam String id) {
        User user = userService.getById(id);
        return Result.ok(user);
    }
    @PostMapping(value = "/updateUser")
    @ApiOperation(value = "更新用户信息", notes = "更新用户信息")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "用户id"),
            @ApiImplicitParam(name = "userName", value = "用户名称"),
            @ApiImplicitParam(name = "file", value = "用户头像"),
            @ApiImplicitParam(name = "phone", value = "用户手机号"),
    })
    public Result<User> updateUser(@RequestParam("file") MultipartFile file,
                                   @RequestParam("id") String id,
                                   @RequestParam("phone") String phone,
                                   @RequestParam("userName") String userName) {
        log.info("更新用户信息:{},{},{},{}", file, id, phone, userName);
        String userURL ="";
        if (file != null) {
            userURL = minioService.upload(file, "userURL");
        }
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getOpenid, id);
        User userDB = userService.getOne(queryWrapper);
        userDB.setId(id);
        userDB.setUserName(userName);
        userDB.setLinkTel(phone);
        userDB.setImgurl(userURL);
        userService.updateById(userDB);
        userDB = userService.getById(id);
        log.info("更新后user:{}",userDB);
        return Result.ok(userDB);
    }
    @PostMapping(value = "/saveUserInfo")
    @ApiOperation(value = "保存用户信息", notes = "保存用户信息")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "用户id"),
            @ApiImplicitParam(name = "phone", value = "用户手机号"),
            @ApiImplicitParam(name = "userName", value = "用户名称"),
    })
    public Result<User> saveUserInfo(@RequestBody Map<String, Object> result) {
        String id = (String) result.get("id");
        String linkTel = (String) result.get("phone");
        String userName = (String) result.get("userName");
        log.info("保存用户信息:{},{},{}", id, linkTel, userName);
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getOpenid, id);
        User userDB = userService.getOne(queryWrapper);
        userDB.setId(id);
        userDB.setLinkTel(linkTel);
        userDB.setUserName(userName);
        userService.updateById(userDB);
        userDB = userService.getById(id);
        log.info("保存后user:{}",userDB);
        return Result.ok(userDB);
    }
    @PostMapping(value = "/getOpenId")
    @ApiOperation(value = "获取用户openId", notes = "获取用户openId")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "code", value = "微信授权码"),
            @ApiImplicitParam(name = "file", value = "用户头像"),
            @ApiImplicitParam(name = "nickName", value = "用户昵称"),
            @ApiImplicitParam(name = "phone", value = "用户手机号码")
    })
    public Result<User> getOpenId(@RequestPart("file") MultipartFile file,
                                  @RequestParam("code") String code,
                                  @RequestParam("nickName") String nickName,
                                  @RequestParam("phone")String  phone) {
        log.info("获取用户code:{},file:{},name:{},phone:{}", code, file, nickName,phone);
        try {
            String wxLoginUrl = "https://api.weixin.qq.com/sns/jscode2session";

            String param = "appid=" + appId + "&secret=" + secret + "&js_code=" + code + "&grant_type=authorization_code";

            String jsonString = GetPostUtil.sendGet(wxLoginUrl, param);
            JSONObject json = new JSONObject(jsonString);
            String openid = json.getString("openid");

            // 将openId存入数据库表（先判断该openId是否在表中已存在，如果不存在，则存入数据库表）
            LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(User::getOpenid, openid);
            User userDB = userService.getOne(queryWrapper);
            if (Objects.isNull(userDB)) {
                String userURL ="";
                if (file != null) {
                    if (phone.equals("123")) {
                        userURL = "https://zhaoyang.mynatapp.cc/imagebucket/userURL/Hlogo.png";
                    }else {
                    userURL = minioService.upload(file, "userURL");
                    }
                }
                // 该openId在表中不存在，则存入数据库表
                User user = new User();
                user.setId(openid);
                user.setUserName(nickName);

                user.setDeleteStatus(0);
                user.setImgurl(userURL);
                user.setAddTime(DateUtils.getNowTime());
                user.setModifyTime(user.getAddTime());
                user.setState(1);  // 设置为游客身份
                user.setOpenid(openid);
                userService.save(user);
                log.info("user:{}",user);
                return Result.ok(user);
            } else {
                log.info("userDB:{}",userDB);
                return Result.ok(userDB);
            }
        }catch (Exception e){
            e.printStackTrace();
            return Result.fail();
        }
    }
}
